/*
 * I'll try to cover all of our AJAX needs in this JS file
 * I've ripped some of the code ehre from the internet, so don't feel surprised if it feels familiar
 **/


/*
 * This method creates the XMLHttpRequest object with the given php page name
 * and the given request string and sends it to the server, and returns it
 * to the given callback function
 */
function sendAJAXRequest(pageName, callBackFunction, postString){
    var req = newXMLHttpRequest();
    var handlerFunction = getReadyStateHandler(req, callBackFunction);
    req.onreadystatechange = handlerFunction;
    req.open("POST", pageName, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Connection", "close");
    req.send(postString);
}

/*
 * Returns a new XMLHttpRequest object, or false if this browser
 * doesn't support it
 */
function newXMLHttpRequest() {
    var xmlreq = false;
    if (window.XMLHttpRequest) {
        // Create XMLHttpRequest object in non-Microsoft browsers
        xmlreq = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // Create XMLHttpRequest via MS ActiveX
        try {
            // Try to create XMLHttpRequest in later versions
            // of Internet Explorer
            xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            // Failed to create required ActiveXObject
            try {
                // Try version supported by older versions
                // of Internet Explorer
                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

            } catch (e2) {
                // Unable to create an XMLHttpRequest with ActiveX
            }
        }
    }
    return xmlreq;
}


/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its JSON response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseHandler - Function to pass the JSON response to
 */
function getReadyStateHandler(req, responseHandler) {
    // Return an anonymous function that listens to the
    // XMLHttpRequest instance
    return function () {
        // If the request's status is "complete"
        if (req.readyState == 4) {
            // Check that a successful server response was received
            if (req.status == 200) {
                //check if the session expired....
                var respTxt;
                var jsonObj;
                try{
                    respTxt = req.responseText;
                    jsonObj = eval('('+respTxt+')');
                    responseHandler(jsonObj);
                } catch(exp) {
                    alert("Error Occured:\n" + exp);
                    responseHandler(null);
                }
            } else {
                // An HTTP problem has occurred
                alert("HTTP Error: "+req.status);
            }
        }
    }
}